package com.panda.admin.login.handler;

import com.panda.admin.result.Result;
import com.panda.admin.result.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * author: tcy
 * description:oauth获取token异常拦截
 */
@RestControllerAdvice
public class AuthExceptionHandler {

    /**
     * 用户不存在
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(UsernameNotFoundException.class)
    public Result<String> handleUsernameNotFoundException(UsernameNotFoundException e) {
        return Result.fail(ResultCode.USER_NOT_EXIST.getMsg());
    }

    /**
     * 密码错误
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidGrantException.class)
    public Result<String> handleInvalidGrantException(InvalidGrantException e) {
        return Result.fail(ResultCode.USERNAME_PASSWORD_ERROR.getMsg());
    }


    /**
     * 账户异常(不存在、禁用及其他异常)
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({InternalAuthenticationServiceException.class})
    public Result<String> handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        return Result.fail(e.getMessage());
    }

    /**
     * token 无效或已过期
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({InvalidTokenException.class})
    public Result<String> handleInvalidTokenExceptionException(InvalidTokenException e) {
        return Result.fail(ResultCode.TOKEN_INVALID_OR_EXPIRED.getMsg());
    }

}
